var currentPage = 1;
var maxPages = 0;
var isTourist = true;
var priceIn = ['$', '&#8362'];
var roomNumber = 1;

var searchHotelsData = {};
var objHotelSearch;
var objHotelLocalName;
var objHotelLocalRate;
var objUserInfo;
var objLocation;
var searchCurrentPage = 1;
var searchMaximumPage;
var maxHotelsInPage = 5;
var isSelectSearch = false;
var sortByArray = ['price', 'rank', 'name'];
var sortBy = 'price';

var obj = {
    100: {
        'Hotel': 'ABC', 
        'Stars': 3, 
        'Rooms': [
            {'Price': [{'bar_price_usd': "80"}]}, 
            {'Price': [{'bar_price_usd': "92"}]}, 
            {'Price': [{'bar_price_usd': "99"}]}
        ], 'Id': 100},
    200: {'Hotel': 'CDF', 'Stars': 5, 'Rooms': [
            {'Price': [{'bar_price_usd': "90"}]}, 
            {'Price': [{'bar_price_usd': "82"}]}, 
            {'Price': [{'bar_price_usd': "100"}]}
        ], 'Id': 200},
    300: {'Hotel': 'AAF', 'Stars': 2, 'Rooms': [
            {'Price': [{'bar_price_usd': "102"}]}, 
            {'Price': [{'bar_price_usd': "73"}]}, 
            {'Price': [{'bar_price_usd': "125"}]},
            {'Price': [{'bar_price_usd': "112"}]}, 
            {'Price': [{'bar_price_usd': "723"}]}, 
            {'Price': [{'bar_price_usd': "145"}]},
            {'Price': [{'bar_price_usd': "302"}]}, 
            {'Price': [{'bar_price_usd': "18"}]}, 
            {'Price': [{'bar_price_usd': "105"}]}
        ], 'Id': 300},
    400: {
        'Hotel': 'ABC', 
        'Stars': 3, 
        'Rooms': [
            {'Price': [{'bar_price_usd': "40"}]}
        ], 'Id': 400},
    500: {'Hotel': 'CDF', 'Stars': 5, 'Rooms': [
            {'Price': [{'bar_price_usd': "44"}]}, 
            {'Price': [{'bar_price_usd': "82"}]}, 
            {'Price': [{'bar_price_usd': "100"}]}
        ], 'Id': 500},
    600: {'Hotel': 'AAF', 'Stars': 2, 'Rooms': [
            {'Price': [{'bar_price_usd': "102"}]}, 
            {'Price': [{'bar_price_usd': "73"}]}
        ], 'Id': 600}
};

$(function() {

//    var bobj = [];
//    $.each(obj, function(i, v) {
//        if ($.isPlainObject(v)) {
//            bobj.push(v);
//        }
//    });
//    sortObjectByPrice(bobj);
//    $.each(bobj, function(i, v) {
//        console.log('--------------');
//        $.each(v.Rooms, function(ii, vv) {
//            console.log(vv.Price[0].bar_price_usd);
//        });
//    });

    //search form
    var nightOption = $('#search_night_input');
    for (var i = 1; i <= 45; i++) {
        if (i === 1) {
            nightOption.append('<option value="' + i + '" selected="selected">' + i + '</option>');
        } else {
            nightOption.append('<option value="' + i + '">' + i + '</option>');
        }
    }

    $('#search_check_in_input').datepicker({
        minDate: getCurrentDate(),
        dateFormat: 'yy-mm-dd',
        onClose: function(selectedDate) {
            var night = $('#search_night_input').val();
            $('#search_check_out_input').val(getOutDate(night, selectedDate));
            $("#search_check_out_input").datepicker("option", "minDate", selectedDate);
        }
    });
    $('.search_check_in img').click(function() {
        $('#search_check_in_input').datepicker("show");
    });
    $('#search_check_out_input').datepicker({
        dateFormat: 'yy-mm-dd',
        onClose: function(selectedDate) {
            $("#search_check_in_input").datepicker("option", "maxDate", selectedDate);
        }
    });
    $('.search_check_out img').click(function() {
        $('#search_check_out_input').datepicker("show");
    });
    $('#search_night_input').on('click', function() {
        if ($('#search_check_in_input').val() !== "") {
            $('#search_check_out_input').val(getOutDate($('#search_night_input').val(), $('#search_check_in_input').val()));
        }
    });
    $('#search_ranks_slider').slider({
        min: 1,
        steep: 1,
        max: 5,
        range: true,
        values: [1, 5]
    });
    //add one first room
    createRoom(roomNumber);
    //add listener to button add room
    $('.add_room').on('click', function() {
        if (roomNumber < 4) {
            roomNumber++;
            createRoom(roomNumber);
        }
    });

    $('.hotel_search_button').on('click', function() {
        search();
    });

    $('.pages_list').on('click', 'ul li', function() {
        if (isSelectSearch) {
            changePage($(this).text());
            return false;
        }
    });

    $('.tabs_sort_by ul li').on('click', function() {
        if (isSelectSearch) {
            changeSort($(this));
            return false;
        }
    });
});

function sortObjectByPrice(object) {
    object.sort(function(a, b) {
        Array.min = function(array) {
            return Math.min.apply(Math, array);
        };
        
        var arrA = [];
        var arrB = [];
        
        $.each(a.Rooms, function(i, v) {
            arrA.push(v.Price.bar_price_usd);
        });
        
        $.each(b.Rooms, function(i, v) {
            arrB.push(v.Price.bar_price_usd);
        });

        var priceA = Array.min(arrA);
        var priceB = Array.min(arrB);
        
        if (priceA < priceB) {
            return -1;
        }

        if (priceA > priceB) {
            return 1;
        }

        return 0;
    });
    
    console.log('aaaa');
}

function sortObjectByName(object) {
    object.sort(function(a, b) {
        var nameA = a.name_en.toLowerCase(), nameB = b.name_en.toLowerCase();
        if (nameA < nameB) {
            return -1;
        }

        if (nameA > nameB) {
            return 1;
        }

        return 0;
    });
}

function sortObjectByRate(object) {
    object.sort(function(a, b) {
        var rateA = a.stars, rateB = b.stars;
        if (rateA < rateB) {
            return 1;
        }

        if (rateA > rateB) {
            return -1;
        }

        return 0;
    });
}

function insertAgeChildren(root) {
    $(root).children('div.search_age_children').remove();
    var ch = $(root).children('div.search_children').children('select').val();
    var bb = $(root).children('div.search_baby').children('select').val();
    var c = parseInt(ch) + parseInt(bb);
    if (c > 0) {
        var search_age_children = $('<div />').addClass('search_age_children').append($('<label />').attr({'for': 'search_age_children_input'}).html('Age of Children'));
        for (var i = 0; i < c; i++) {
            var search_age_children_input = $('<input />').addClass('search_age_children_input');
            (search_age_children).append(search_age_children_input);
        }
        $(root).append(search_age_children);
    }
}

function createRoom(roomNumber) {
    if (roomNumber === 1) {
        $('.center_line_rooms .center_line').remove();
    }
    var center_line_rooms = $('.center_line_rooms');
    var center_line = $('<div />').addClass('center_line').attr({'room': roomNumber});
    var search_room = $('<div />').addClass('search_room').append($('<label />').attr({'for': 'search_room_number'}).html('Room')).
            append($('<input />').attr({'type': 'text', 'class': 'search_room_number', 'value': roomNumber, 'readonly': 'true'}));
    var search_adult = $('<div />').addClass('search_adult').append($('<label />').attr({'for': 'search_adult_select'}).html('Adults'));
    var select = $('<select />').addClass('search_adult_select');
    for (var i = 0; i < 6; i++) {
        var option;
        if (i === 2) {
            option = $('<option selected="selected" value="' + i + '">' + i + '</option>');
        } else {
            option = $('<option value="' + i + '">' + i + '</option>');
        }

        (select).append(option);
    }


    (search_adult).append(select);
    var search_children = $('<div />').addClass('search_children').append($('<label />').attr({'for': 'search_children_select'}).html('Children'));
    select = $('<select />').addClass('search_children_select').attr({'id': 'select_room_children_' + roomNumber});
    for (var i = 0; i < 3; i++) {
        var option;
        if (i === 0) {
            option = $('<option selected="selected" value="' + i + '">' + i + '</option>');
        } else {
            option = $('<option value="' + i + '">' + i + '</option>');
        }

        (select).append(option);
    }

    (search_children).append(select);
    var search_baby = $('<div />').addClass('search_baby').append($('<label />').attr({'for': 'search_baby_select'}).html('Babies'));
    select = $('<select />').addClass('search_baby_select').attr({'id': 'select_room_babies_' + roomNumber});
    for (var i = 0; i < 3; i++) {
        var option;
        if (i === 0) {
            option = $('<option selected="selected" value="' + i + '">' + i + '</option>');
        } else {
            option = $('<option value="' + i + '">' + i + '</option>');
        }

        (select).append(option);
    }

    (search_baby).append(select);
    (center_line_rooms).append((center_line).append(search_room).append(search_adult).append(search_children).append(search_baby));
    $('#select_room_children_' + roomNumber).change(function() {
        insertAgeChildren($(this).parent().parent());
    });
    $('#select_room_babies_' + roomNumber).change(function() {
        insertAgeChildren($(this).parent().parent());
    });
}

function search() {
    if (parseInt($('.search_city select').val()) === 0) {
        $('#search_city_select').css({border: '1px solid #f10909'});
        $('.search_city label').css({color: '#f10909'});
        isSelectSearch = false;
        return;
    } else {
        $('#search_city_select').css({border: '1px solid #b9b9b9'});
        $('.search_city label').css({color: '#6d6d6d'});
    }

    var date_in = $('#search_check_in_input').val();
    if (!date_in) {
        date_in = getCurrentDate();
    }

    var date_out = $('#search_check_out_input').val();
    if (!date_out) {
        date_out = getOutDate($('#search_night_input').val(), date_in);
    }

    var roomsString = '';
    $('.center_line_rooms .center_line').each(function(i, v) {
        roomsString = roomsString + (i + 1) + ':' + $(v).children('div.search_adult').children('select').val() + ':' +
                $(v).children('div.search_children').children('select').val() + ':' + $(v).children('div.search_baby').children('select').val() + ';';
    });
    searchHotelsData = {
        city: $('.search_city select').val(),
        hotel: $('.search_hotels select').val(),
        date_in: date_in,
        days: $('#search_night_input').val(),
        date_out: date_out,
        stars: $('#search_ranks_slider').slider("values"),
        rooms: roomsString,
        civic: $('input[name=group_civic]:checked', '.user_civic').val()
    };
    $.ajax({
        type: 'POST',
        url: urlBackend + 'searchhotels',
        data: searchHotelsData,
        beforeSend: function() {
            showLoaderHotels();
        },
        success: function(response) {
            var json = $.parseJSON(response);
            $(json).each(function(i, v) {
                objHotelSearch = parseObj(v.search);
                objHotelLocalName = v.local_name;
                objHotelLocalRate = v.local_rate;
                objLocation = v.location;
                objUserInfo = v.user;
                insertHotels(objHotelSearch, v.local_name, searchCurrentPage, sortByArray[0]);
                paging(objHotelSearch, v.local_name);
                isSelectSearch = true;
                hideLoaderHotels();
            });
        }
    });
}

function parseObj(object) {
    var newObject = [];
    $.each(object, function(i, v) {
        if ($.isPlainObject(v)) {
            newObject.push(v.Hotel);
        }
    });
    return newObject;
}

function sortHotels(objHotels, type) {
    var local;
    switch (type) {
        case sortByArray[0]:
            sortObjectByPrice(objHotels);
            local = objHotelLocalName;
        case sortByArray[1]:
            sortObjectByRate(objHotels);
            local = objHotelLocalRate;
            break;
        case sortByArray[2]:
            sortObjectByName(objHotels);
            local = objHotelLocalName;
            break;
    }
    
    insertHotels(objHotels, local, searchCurrentPage, type);
    paging(objHotels, local);
}

function insertHotels(search, local, page, sort) {
    var maxHotelsToPage = maxHotelsInPage; // get 5 hotels to page
    var showFrom = (page * maxHotelsToPage) - maxHotelsToPage; // get first hotel from object hotels
    var showTo = showFrom + maxHotelsToPage; // get last hotel from object hotels
    var countShowHotels = 0; // count hotels added to current page
    var countStart = 0; // counter start add hotels to page

    var stars = [
        '/travis/web/images/icoStar.png',
        '/travis/web/images/icoStars2.png',
        '/travis/web/images/icoStars3.png',
        '/travis/web/images/icoStars4.png',
        '/travis/web/images/icoStars5.png'
    ];
    var defaultLanguage = 'en';
    var defaultPrice = '$';
    if (parseInt(objUserInfo.civic) === 2) {
        defaultPrice = '&#8362';
    }
    $('.hotel_container div').remove(); // delete current hotels list in page
    var hotel_container = $('.hotel_container'); // main conteiner
    var hotel_blocks = $('<div />').addClass('hotel_blocks'); // second container
    var hotel_container_clear = $('<div style="clear: both"></div>'); // restore size to main container

    $.each(search, function(name, hotel) {
        if (countStart >= showFrom && countStart < showTo) {
            var row_one_container = $('<div />').addClass('row_one_container');
            var row_two_container = $('<div />').addClass('row_two_container');
            var row_three_container = $('<div />').addClass('row_three_container');
            // insert image one if exists, else default image
            var image = hotel.photo;
            if (image == null || image == '') {
                image = '/travis/web/uploads/no_image.png';
            } else {
                var images = image.split(';');
                image = images[0];
            }

            var image_container_hotel = $('<div />').addClass('image_container_hotel')
                    .append($('<a href="' + urlBackend + '/hotel/id/' + hotel.id + '"><img src="' + image + '"/></a>'))
                    .append($('<div />').html(hotel.description_en));
            (row_three_container).append(image_container_hotel);
            //insert hotel title
            var rooms_container_hotel = $('<div />').addClass('rooms_container_hotel')
                    .append($('<div />').addClass('rooms_title').append($('<div />').addClass('hotel_description')
                            .append($('<div />').addClass('hotel_name').append('<a href="' + urlBackend + '/hotel/id/' + hotel.id + '">' + hotel.name_en + '</a>')
                                    .append($('<img src="' + stars[parseInt(hotel.stars) - 1] + '"/>')))
                            .append($('<div />').addClass('hotel_location_one').html(objLocation.Country.name_en + ' ' + objLocation.Region.name_en))
                            .append($('<div />').addClass('hotel_location_two').html(objLocation.City.name_en))));
            //insert title rooms
            var rooms_title_description = $('<div />').addClass('rooms_title_description')
                    .append($('<div />').addClass('rtd_room').html('Room'))
                    .append($('<div />').addClass('rtd_people').html('Adult/Children/Babies'))
                    .append($('<div />').addClass('rtd_boarding').html('Usual Boarding'))
                    .append($('<div />').addClass('rtd_price').html('Price')); // this place to insert agent commissions
            (rooms_container_hotel).append(rooms_title_description);
            //insert rooms
            var minmaxprice = [];
            $.each(hotel.Rooms, function(key, room) {
                var rooms_full_description = $('<div />').addClass('rooms_full_description')
                        .append($('<div />').addClass('rfd_room').attr({title: room.description_en}).html(room.name))
                        .append($('<div />').addClass('rfd_people').html(room.adult + ' | ' + room.children + ' | ' + room.baby))
                        .append($('<div />').addClass('rfd_boarding').html(room.Price.meal_name))
                        .append($('<div />').addClass('rfd_price').html(room.Price.bar_price_usd + defaultPrice));
                (rooms_container_hotel).append(rooms_full_description);
                minmaxprice.push(room.Price.bar_price_usd);
            });
            (row_three_container).append(rooms_container_hotel);
            //find min - max price
            Array.max = function(array) {
                return Math.max.apply(Math, array);
            };
            Array.min = function(array) {
                return Math.min.apply(Math, array);
            };
            //price container
            var btnUrl = urlBackend + 'hotel/id/' + hotel.id + '/date/' + searchHotelsData.date_in + '/night/' + searchHotelsData.days + '/stars/'
                    + searchHotelsData.stars + '/rooms/' + searchHotelsData.rooms;
            var price_container_hotel = $('<div />').addClass('price_container_hotel')
                    .append($('<div />').addClass('price_title').append($('<div />').addClass('price_more_info')
                            .append($('<a href="' + urlBackend + 'hotel/id/' + hotel.id + '"><ul><li>Map</li><li> | </li><li>Hotel info</li></ul></a>')))
                            .append($('<div />').addClass('price_avg').html(Array.min(minmaxprice) + defaultPrice + ' - ' + Array.max(minmaxprice) + defaultPrice)))
                    .append($('<div />').addClass('price_total_container').append($('<div />').addClass('vertical_seporator')
                            .append($('<div />').addClass('price_booking_btn')
                                    .append($('<a href="' + btnUrl + '">Reserve It</a>')))));
            (row_three_container).append(price_container_hotel);

            (hotel_blocks).append((row_one_container).append((row_two_container).append(row_three_container)));
            countShowHotels++;
        }

        countStart++;
    });

    if (countShowHotels < maxHotelsToPage - 1) {
        $.each(local, function(i, v) {
            if ($.isPlainObject(v)) {
                $.each(v, function(name, hotel) {
                    if (countStart >= showFrom && countStart < showTo) {
                        var row_one_container = $('<div />').addClass('row_one_container');
                        var row_two_container = $('<div />').addClass('row_two_container');
                        var row_three_container = $('<div />').addClass('row_three_container');
                        // insert image one if exists, else default image
                        var image = hotel.photo;
                        if (image == null || image === '') {
                            image = '/travis/web/uploads/no_image.png';
                        } else {
                            var images = image.split(';');
                            image = images[0];
                        }

                        var image_container_hotel = $('<div />').addClass('image_container_hotel')
                                .append($('<a href="' + urlBackend + '/hotel/id/' + hotel.id + '"><img src="' + image + '"/></a>'))
                                .append($('<div />').html(hotel.description_en));
                        (row_three_container).append(image_container_hotel);
                        //insert hotel title
                        var rooms_container_hotel = $('<div />').addClass('rooms_container_hotel')
                                .append($('<div />').addClass('rooms_title').append($('<div />').addClass('hotel_description')
                                        .append($('<div />').addClass('hotel_name').append('<a href="' + urlBackend + '/hotel/id/' + hotel.id + '">' + hotel.name_en + '</a>')
                                                .append($('<img src="' + stars[parseInt(hotel.stars) - 1] + '"/>')))
                                        .append($('<div />').addClass('hotel_location_one').html(objLocation.Country.name_en + ' ' + objLocation.Region.name_en))
                                        .append($('<div />').addClass('hotel_location_two').html(objLocation.City.name_en))));
                        //insert title rooms
                        var rooms_title_description = $('<div />').addClass('rooms_title_description')
                                .append($('<div />').addClass('rtd_room').html('Room'))
                                .append($('<div />').addClass('rtd_people').html('Adult/Children/Babies'))
                                .append($('<div />').addClass('rtd_boarding').html('Usual Boarding'))
                                .append($('<div />').addClass('rtd_price').html('Price')); // this place to insert agent commissions
                        (rooms_container_hotel).append(rooms_title_description);
                        //insert not avalible rooms
                        var rooms_full_description = $('<div />').addClass('rooms_full_description')
                                .append($('<div />').addClass('rfd_not_available').html('Unfortunately, there are no empty rooms for this date. You can ask the admin and we will try to help you.'));
                        (rooms_container_hotel).append(rooms_full_description);
                        (row_three_container).append(rooms_container_hotel);

                        //price container
                        var btnUrl = '';
                        var price_container_hotel = $('<div />').addClass('price_container_hotel')
                                .append($('<div />').addClass('price_title').append($('<div />').addClass('price_more_info')
                                        .append($('<a href="' + urlBackend + 'hotel/id/' + hotel.id + '"><ul><li>Map</li><li> | </li><li>Hotel info</li></ul></a>')))
                                        .append($('<div />').addClass('price_avg').html('---')))
                                .append($('<div />').addClass('price_total_container').append($('<div />').addClass('vertical_seporator')
                                        .append($('<div />').addClass('price_booking_btn')
                                                .append($('<a href="' + btnUrl + '">Ask the Admin</a>')))));
                        (row_three_container).append(price_container_hotel);

                        (hotel_blocks).append((row_one_container).append((row_two_container).append(row_three_container)));
                        countShowHotels++;
                    }

                    countStart++;
                });
            }
        });
    }

    (hotel_container).append(hotel_blocks);
    (hotel_container).append(hotel_container_clear);
}

function paging(search, local) {
    var hotelsCount = 0;
    var availableHotels = 0;
    $.each(search, function(i, v) {
        hotelsCount++;
    });

    availableHotels = hotelsCount;

    $.each(local, function(i, v) {
        if ($.isPlainObject(v)) {
            $.each(v, function(ii, vv) {
                hotelsCount++;
            });
        }
    });

    searchMaximumPage = Math.ceil(hotelsCount / maxHotelsInPage);
    insertStringSearch(availableHotels, hotelsCount);
    insertPages(searchMaximumPage, searchCurrentPage);
}

function insertStringSearch(available, all) {
    $('.right_header_block').html(available + ' available hotels among ' + all);
}

function insertPages(maxPages, currentPage) {
    $('.pages_list ul').remove();
    var list = $('.pages_list');
    var ul = $('<ul />').append($('<li />').text('<<'));

    if (parseInt(maxPages) < 10) {
        for (var p = 0; p < maxPages; p++) {
            if (parseInt(currentPage) === p + 1) {
                var li = $('<li />').addClass('active').text(p + 1);
            } else {
                var li = $('<li />').text(p + 1);
            }
            (ul).append(li);
        }
    } else {
        if (parseInt(currentPage) < 6) {
            for (var p = 0; p < 9; p++) {
                if (parseInt(currentPage) === p + 1) {
                    var li = $('<li />').addClass('active').text(p + 1);
                } else {
                    var li = $('<li />').text(p + 1);
                }
                (ul).append(li);
            }

            (ul).append($('<li />').text('...')).append($('<li />').text(maxPages));
        } else if (parseInt(maxPages) - parseInt(currentPage) < 5) {
            (ul).append($('<li />').text(1)).append($('<li />').text('...'));
            for (var p = maxPages - 9; p < maxPages; p++) {
                if (parseInt(currentPage) === p + 1) {
                    var li = $('<li />').addClass('active').text(p + 1);
                } else {
                    var li = $('<li />').text(p + 1);
                }
                (ul).append(li);
            }
        } else {
            (ul).append($('<li />').text(1)).append($('<li />').text('...'));
            for (var p = parseInt(currentPage) - 5; p < parseInt(currentPage); p++) {
                if (parseInt(currentPage) === p + 1) {
                    var li = $('<li />').addClass('active').text(p + 1);
                } else {
                    var li = $('<li />').text(p + 1);
                }
                (ul).append(li);
            }

            for (var p = parseInt(currentPage); p < (parseInt(currentPage) + 4); p++) {
                (ul).append($('<li />').text(p + 1));
            }
            (ul).append($('<li />').text('...')).append($('<li />').text(maxPages));
        }
    }
    (ul).append($('<li />').text('>>'));
    (list).append(ul);
}

function changePage(page) {
    if (page == '<<') {
        if (searchCurrentPage > 1) {
            searchCurrentPage--;
        }
    } else if (page == '>>') {
        if (searchCurrentPage < searchMaximumPage) {
            searchCurrentPage++;
        }
    } else {
        searchCurrentPage = page;
    }

    var localHotels = objHotelLocalName;
    if (sortBy === sortByArray[1]) {
        localHotels = objHotelLocalRate;
    }

    insertHotels(objHotelSearch, localHotels, searchCurrentPage, sortBy);
    insertPages(searchMaximumPage, searchCurrentPage);
}

function changeSort(sort) {
    sortBy = $(sort).attr('value');
    searchCurrentPage = 1;

    sortHotels(objHotelSearch, sortBy);

    $('.tabs_sort_by ul').find('li.active').removeClass('active');
    $(sort).addClass('active');
}

function showLoaderHotels() {
    var winWidth = $(window).width();
    var winHeight = $(window).height();

    $('#blackout').css({'width': winWidth + 'px', 'height': winHeight + 'px'});
    $('#blackout').show();

    var boxWidth = 300;
    var disWidth = (winWidth - boxWidth) / 2;
    var disHeight = (winHeight - 125) / 2;
    $('#show_loader_hotels').css({'width': boxWidth + 'px', 'left': disWidth + 'px', 'top': disHeight + 'px'});
    $('#show_loader_hotels').show();
}

function hideLoaderHotels() {
    $('#blackout').css({'width': 0 + 'px', 'height': 0 + 'px'});
    $('#blackout').hide();

    $('#show_loader_hotels').hide();
}



